<template>
  <div class="wu-table">
    <!-- v-model:queryForm="tableModule.queryForm" -->
    <div class="table-top">
      <el-row>
        <el-col
          v-if="tableModule?.formItemList"
          :lg="hasTopActions ? 18 : 24"
          :xs="24"
        >
          <wu-search-form
            ref="searchForm"
            :form-item-list="tableModule.formItemList"
            @search="search"
            @reset="reset"
          ></wu-search-form>
        </el-col>
        <!-- lg>1200以上才和searchForm一行，否则占满 -->
        <el-col :lg="hasTopActions ? 6 : 0" :xs="24" class="top-actions">
          <!-- 头部配置操作按钮 -->
          <template
            v-if="tableModule?.topActions && tableModule?.topActions.length > 0"
          >
            <el-button
              v-for="(item, index) in tableModule?.topActions"
              :key="index"
              :type="item.type"
              @click="item.clickFun && item.clickFun()"
            >
              <el-icon class="top-action-icon" v-if="item.icon">
                <component :is="item.icon" />
              </el-icon>
              {{ item?.text }}
            </el-button>
          </template>
          <!-- 头部操作插槽 -->
          <slot name="topActions"></slot>
        </el-col>
      </el-row>
    </div>
    <!-- $attrs：接收props遗漏的attr属性 -->
    <el-table v-bind="$attrs" :data="tableData" style="width: 100%">
      <template v-for="item in tableModule.columns" :key="item.prop">
        <!-- 操作列 -->
        <el-table-column
          v-if="item.actions"
          :prop="item.prop"
          :label="item.label"
          :width="item.width || '150px'"
          :fixed="item.fixed || 'right'"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <!-- 图标按钮 -->
              <ActionButton
                v-for="action in item.actions"
                :key="action.text"
                :icon="action?.icon"
                :text="action.text"
                :click-fun="() => action?.clickFun && action?.clickFun(scope)"
              ></ActionButton>
            </div>
          </template>
        </el-table-column>
        <!-- 普通列+插槽列 -->
        <el-table-column
          v-else-if="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth || ''"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <slot
              v-if="item.slotName"
              :name="item.slotName"
              v-bind="scope"
            ></slot>
            <template v-else-if="item.type === 'image'">
              <el-image
                :src="scope.row[item.prop]"
                :preview-src-list="[scope.row[item.prop]]"
                preview-teleported
                fit="contain"
                style="width: 60px; height: 60px"
              />
            </template>
            <!-- 枚举：后期改进 -->
            <template v-else-if="item.type === 'enum'">
              <el-tag v-if="item.enumDict?.[scope.row[item.prop]]">
                {{ item.enumDict?.[scope.row[item.prop]] }}
              </el-tag>
              <span v-else>{{ item.enumDict?.[scope.row[item.prop]] }}</span>
            </template>
            <template v-else>{{ scope.row[item.prop] }}</template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- 分页 -->
    <div v-if="pageOption.showPage" class="page-wrap">
      <div class="page-action">
        <!-- 表格底部按钮 -->
        <slot name="bottomActions"></slot>
      </div>
      <el-pagination
        v-model:current-page="queryFormData[pageOption.pageNumKey]"
        v-model:page-size="queryFormData[pageOption.pageSizeKey]"
        :page-sizes="pageOption.pageSizes"
        :small="pageOption.small"
        :disabled="pageOption.disabled"
        :background="pageOption.background"
        :layout="pageOption.layout"
        :total="pageOption.total || 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { tableModuleType, pageType } from '@/types/wu-table'
import { isEmptyData } from '@/utils'
const props = defineProps<{
  tableModule: tableModuleType
}>()
/**
 * emits 事件钩子
 * onGetList 监听获取列表list
 */
const emits = defineEmits(['onGetList'])
const slots = useSlots()
console.log('slots', slots)
// 是否有顶部操作按钮
const hasTopActions = computed(() => {
  let slotflag = slots?.topActions
  let propflag =
    props.tableModule?.topActions && props.tableModule?.topActions.length > 0
  return propflag || slotflag
})
// page初始值
const pageOption = ref<pageType>({} as pageType)
type queryFormType = typeof props.tableModule.queryForm

// searchForm表单事件监听
const searchForm = ref()
const search = (searchForm: queryFormType) => {
  Object.assign(queryFormData.value, searchForm)
  getListApiFun()
}
const reset = (searchForm: queryFormType) => {
  Object.assign(queryFormData.value, searchForm)
  getListApiFun()
}
// 手动search 触发searhForm组件search事件
const manualSearch = () => {
  if (searchForm.value) {
    // 是否有searchForm
    searchForm.value?.onSearch()
  } else {
    getListApiFun()
  }
}

// table列表数据
const tableData = ref([])
// 获取列表数据
const getListApiFun = async () => {
  const { getListApi } = props.tableModule
  const staticTableData: any = props.tableModule.staticTableData
  let result = null
  if (!isEmptyData(getListApi)) {
    // 动态数据
    result = await getListApi?.({ ...queryFormData.value })
    tableData.value = result.data?.records || []
    pageOption.value.total = result.data?.total || 0
  } else if (!isEmptyData(staticTableData)) {
    // 静态数据
    tableData.value = staticTableData
    result = { data: { records: staticTableData } }
  }

  emits('onGetList', result)
}
const queryFormData = ref({} as queryFormType)
/**
 * page分页
 */
const initPage = () => {
  const { page } = props.tableModule
  pageOption.value = {
    showPage: isEmptyData(page?.showPage) ? true : page?.showPage,
    pageNumKey: page?.pageNumKey || 'pageNum',
    pageSizeKey: page?.pageSizeKey || 'pageSize',
    total: 0,
    small: page?.['small'] || true,
    disabled: page?.['disabled'] || false,
    background: page?.['background'] || false,
    layout: page?.['layout'] || 'total, sizes, prev, pager, next, jumper',
    pageSizes: page?.['pageSizes'] || [5, 10, 50, 100, 500]
  }

  if (pageOption.value.showPage) {
    // queryFormData分页参数初始化
    queryFormData.value = {
      [pageOption.value.pageNumKey]: 1,
      [pageOption.value.pageSizeKey]: 10
    }
  }
}
// 分页数据change
const handleSizeChange = (val: number) => {
  queryFormData.value[pageOption.value.pageSizeKey] = val
  getListApiFun()
}
const handleCurrentChange = (val: number) => {
  queryFormData.value[pageOption.value.pageNumKey] = val
  getListApiFun()
}
// table数据queryFormData初始化
const initData = () => {
  const { queryForm } = props.tableModule
  // page初始化
  initPage()
  // queryForm作为初始值
  Object.assign(queryFormData.value, queryForm)
}
// 实例创建完毕后,立即初始化数据
initData()
onMounted(() => {
  // 首次调用-带搜索参数
  manualSearch()
})
defineExpose({
  queryForm: queryFormData.value
})
</script>

<style lang="scss" scoped>
.page-wrap {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.top-actions {
  display: flex;
  // flex-flow: row wrap;
  flex-direction: row;
  align-items: flex-end;
  justify-content: flex-end;
  margin-bottom: 10px;

  :deep(.el-button) {
    margin-bottom: 8px;

    .top-action-icon {
      margin-right: 2px;
    }
  }
}
</style>
